import Point from "@/plugins/Point.js";
import TIN from "@/plugins/TIN.js";
import arrayMaxValue from "@/common/arrayMaxValue.js";
import arrayMinValue from "@/common/arrayMinValue.js";
import defaultValue from "@/common/defaultValue.js";
import defined from "@/common/defined.js";

//记录xyz坐标值
function Cartesian3(x, y, z) {
  this.x = defaultValue(x, 0.0);
  this.y = defaultValue(y, 0.0);
  this.z = defaultValue(z, 0.0);
}

function queryAdjoinTINs(tin, tinSet = []) {
  const adjointTINs = [null, null, null];
  if (!defined(tin)) return adjointTINs;
  const length = tinSet.length;
  for (let i = 0; i < length; i++) {
    const curTIN = tinSet[i];
    if (tin === curTIN) {
      continue;
    }
  }
  return adjointTINs;
}
function createTINSet(workerData) {
  if (!defined(workerData)) return [];
  try {
    const tinSet = [];
    const { indieList, vertexList, altitudeList } = workerData || {};
    const maxAltitude = arrayMaxValue(altitudeList),
      minAltitude = arrayMinValue(altitudeList);
    for (let i = 0; i < indieList.length; i += 3) {
      const idx_1 = indieList[i + 2],
        idx_2 = indieList[i + 1],
        idx_3 = indieList[i];
      const p1 = new Cartesian3(
          vertexList[idx_1 * 3],
          vertexList[idx_1 * 3 + 1],
          vertexList[idx_1 * 3 + 2]
        ),
        p2 = new Cartesian3(
          vertexList[idx_2 * 3],
          vertexList[idx_2 * 3 + 1],
          vertexList[idx_2 * 3 + 2]
        ),
        p3 = new Cartesian3(
          vertexList[idx_3 * 3],
          vertexList[idx_3 * 3 + 1],
          vertexList[idx_3 * 3 + 2]
        );
      const [height1, height2, height3] = [
        altitudeList[i + 2],
        altitudeList[i + 1],
        altitudeList[i],
      ];
      const vertex1 = new Point(p1, height1),
        vertex2 = new Point(p2, height2),
        vertex3 = new Point(p3, height3);
      const tin = new TIN([idx_1, idx_2, idx_3], [vertex1, vertex2, vertex3]);
      tinSet.push(tin);
    }
    for (let i = 0; i < tinSet.length; i++) {
      const curTIN = tinSet[i];
      tinSet[i].adjointTINs = queryAdjoinTINs(curTIN, tinSet);
    }
    return {
      tinSet: tinSet,
      maxAltitude: maxAltitude,
      minAltitude: minAltitude,
    };
  } catch (err) {
    return {};
  }
}
onmessage = function (msg) {
  const workerData = msg.data;
  try {
    const workerResult = createTINSet(workerData);
    postMessage({ msg: "success", code: 200, data: workerResult });
  } catch (err) {
    postMessage({ msg: "error" || err?.message, code: 500, data: null });
  }
};
